<template>
  <div class="_single-digi-scroller">
    <div class="placeholder" ref="myPlaceHolder">0</div>
    <div class="display-panel" :style="panelStyle" ref="myDigiPanel">
      <div class="num" :style="panelStyle">0</div>
      <div class="num" :style="panelStyle">1</div>
      <div class="num" :style="panelStyle">2</div>
      <div class="num" :style="panelStyle">3</div>
      <div class="num" :style="panelStyle">4</div>
      <div class="num" :style="panelStyle">5</div>
      <div class="num" :style="panelStyle">6</div>
      <div class="num" :style="panelStyle">7</div>
      <div class="num" :style="panelStyle">8</div>
      <div class="num" :style="panelStyle">9</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "SingleNumberRoll",
  data() {
    return {
      toPos: false,
      fromPos: false,
      transitionStyle: {}
    }
  },
  props: {
    from: {
      type: [Number, String],
      default: 0
    },
    to: {
      type: [Number, String],
      default: 0
    },
    height: {
      type: [Number, String],
      default: 0
    },
    speed: {
      type: [Number, String],
      default: 2
    }
  },
  methods: {

  },
  watch: {
    changeInfo: {
      immediate: true,
      handler(val) {
        if (val) {
          this.fromPos = { top: `-${(val.from * this.height) }px` };
          setTimeout(() => {
            // 不用nexttick是因为其间隔太小，浏览器未渲染就改变了pos，导致动画没生效
            this.toPos = { top: `-${(val.to * this.height) }px` };
            this.transitionStyle = { transition: `${this.speed}s` };
          }, 200);
        }
      }
    }
  },
  computed: {
    numStyle() {
      return {
        height: `${this.height}px`,
        lineHeight: `${this.height}px`
      };
    },
    panelStyle() {
      if (this.toPos) return { ...this.toPos, ...this.transitionStyle };
      if (this.fromPos) return { ...this.fromPos, ...this.transitionStyle };
      return {};
    },
    changeInfo() {
      if ((this.from || this.from === 0) && (this.to || this.to === 0)) {
        return { to: this.to, from: this.from };
      }
      return false;
    }
  },
  mounted() {
    this.$refs.myPlaceHolder.style.height = this.height;
  }
}
</script>

<style>
._single-digi-scroller {
  display: inline-block;
  position: relative;
  overflow: hidden;
}

.placeholder {
  opacity: 0;
}

.display-panel {
  position: absolute;
}
</style>